package com.base.cn.platform.os.common.controller;

import com.base.cn.platform.os.common.tools.DateEditor;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 基础的
 */
public abstract class BaseController {

    public Logger logger = LoggerFactory.getLogger(this.getClass());
    public Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    @InitBinder
    public void initDate(WebDataBinder binder){
        binder.registerCustomEditor(Date.class, new DateEditor());
    }

    /**
     * 获取所有请求的参数
     * @param request HttpServletRequest
     * @return Map<String,Object> ,如果是多个值会转成：value=val1,val2,val3
     */
    public Map<String,Object> getParamsMap(HttpServletRequest request){
        Enumeration<String> paramNames = request.getParameterNames();
        Map<String,String[]> paramsMap = new HashMap<>();
        while (paramNames.hasMoreElements()){
            String name = paramNames.nextElement();
            String[] values = request.getParameterValues(name);
            paramsMap.put(name,values);
        }
        Map<String,Object> params = new HashMap<>();
        if(ObjectUtils.isNotEmpty(paramsMap)){
            paramsMap.forEach((k,v)->{
                if(ObjectUtils.isNotEmpty(v) && v.length>0){
                    String values = Arrays.stream(v).map(e->e).collect(Collectors.joining(","));
                    params.put(k,values);
                }
            });
        }
        return params;
    }

    /**
     * 设置重定向
     * @param request
     * @param path
     * @return
     */
    public String redirect(HttpServletRequest request,String path){
        String contextPath = request.getContextPath();
        if(StringUtils.isEmpty(contextPath) || path.startsWith("http://") || path.startsWith("https://") || contextPath.equals("/")){
            return "redirect:"+path;
        }else{
            return "redirect:"+(contextPath + path).replaceAll("//","/");
        }
    }
}
